<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="ruleList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          align="center"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="30%">
      <el-form
        :model="ruleForm"
        :rules="ruleFormRules"
        ref="ruleFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="职位" prop="position">
          <el-select v-model="ruleForm.position" placeholder="请选择职位">
            <el-option
              v-for="position in positions"
              :key="position.value"
              :label="position.label"
              :value="position.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="利润比例" prop="ratio">
          <el-input
            type="number"
            step="1"
            v-model="ruleForm.ratio"
            placeholder="输入利润比例"
            clearable
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="HandleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRuleList, addRule, updateRule, delRule } from "@/api/employee";
import { positions } from "@/utils/const";

const defaultForm = {
  id: undefined,
  position: "",
  ratio: 0,
};

export default {
  name: "Rule",
  data() {
    return {
      ruleForm: Object.assign({}, defaultForm),
      ruleFormRules: {
        position: [{ required: true, message: "请选择职位", trigger: "blur" }],
        ratio: [{ required: true, message: "请输入利润比例", trigger: "blur" }],
      },
      title: "分配规则",
      dialogVisible: false,
      dialogType: "new",
      ruleList: [],
      listLoading: true,
      tableColumns: [
        {
          key: "position_name",
          title: "职位",
        },
        {
          key: "ratio",
          title: "比例(%)",
        },
      ],
      positions: positions,
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  created() {
    this.getRules();
  },
  methods: {
    getRules() {
      this.listLoading = true;
      getRuleList()
        .then((res) => {
          this.ruleList = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    // 增加银行账户
    handleAdd() {
      this.ruleForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.ruleFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.ruleForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.ruleFormRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delRule(row.id);

          this.ruleList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          res = await updateRule(this.ruleForm);
          console.log(isEdit, res);
          const index = this.ruleList.findIndex((v) => v.id === res.id);
          this.ruleList.splice(index, 1, res);
        } else {
          res = await addRule(this.ruleForm);
          const { id } = res;
          if (id > 0) {
            this.getRules();
          }
        }

        const { position_name, ratio } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>职位: ${position_name}</div>
              <div>利润比例: ${ratio}%</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}
</style>